﻿Imports System.IO
Imports System.Net
Imports System.Text
Imports AutoUpdaterDotNET

Public Class LoginForm
    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
        If UsernameTextBox.TextLength = 0 Then
            UsernameTextBox.Select()
            Exit Sub
        End If
        Dim client As New WebClient()
        client.QueryString.Add("user", UsernameTextBox.Text)
        client.QueryString.Add("pass", PasswordTextBox.Text)
        Dim IOStream = client.OpenRead(New Uri(Urls.API_LOGIN))
        Using stream = New StreamReader(IOStream, Encoding.UTF8)
            Dim json As String = stream.ReadToEnd
            Console.WriteLine(json)
            Dim user As User = JsonClass.DeserializeJsonToObject(Of User)(json)
            If user Is Nothing Then
                MsgBox(json)
                Exit Sub
            End If
            My.Settings.username = UsernameTextBox.Text
            My.Settings.Save()
            Dim frm As New Form2(user)
            frm.Show()
            Me.Hide()
        End Using
    End Sub

    Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
        Me.Close()
    End Sub

    Private Sub LoginForm_Load(sender As Object, e As EventArgs) Handles Me.Load
        CheckForIllegalCrossThreadCalls = False
        AutoUpdater.CurrentCulture = Application.CurrentCulture
        AutoUpdater.AppCastURL = Urls.API_SOFT_UPDATE
        AddHandler AutoUpdater.UpdateStatus, AddressOf updateStatusSub
        AutoUpdater.Start(0)
        If String.IsNullOrWhiteSpace(My.Settings.username) = False Then
            UsernameTextBox.Text = My.Settings.username
        End If
        OK.Enabled = False
        Dim siteResponds = My.Computer.Network.Ping(Urls.HOST_IP)
        If siteResponds Then
            OK.Enabled = True
        End If
    End Sub

    Private Sub updateStatusSub(sender As Object, e As AutoUpdateEventArgs)

    End Sub
End Class
